package com.shepin.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.shepin.R;

public class MainActivity extends FragmentActivity implements OnClickListener {

	private ImageView index, category, cart, my;

	private FragmentManager manager;
	private FragmentTransaction transaction;

	private int currType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_activity);

		index = (ImageView) findViewById(R.id.ShouYe);
		category = (ImageView) findViewById(R.id.FenLei);
		cart = (ImageView) findViewById(R.id.GouWu);
		my = (ImageView) findViewById(R.id.Wo);
		
		manager = getSupportFragmentManager();

		index.setOnClickListener(this);
        index.setImageResource(R.drawable.icon1);
		category.setOnClickListener(this);
		cart.setOnClickListener(this);
		my.setOnClickListener(this);
		SuiPian(1);
	}

	private void SuiPian(int Byid) {
		if (Byid == currType) {
			return;
		}

		transaction = manager.beginTransaction();

		Fragment fra = manager.findFragmentByTag("ss" + Byid);
		if (fra == null) {
			if (Byid == 1) {
				fra = new IndexActivity();
			} else if (Byid == 2) {
				fra = new CategoryActivity();
			} else if (Byid == 3) {
				fra = new CartActivity();
			} else if (Byid == 4) {
				fra = new MyActivity();
			}
			transaction.add(R.id.Fra, fra, "ss" + Byid);
		} else {
			if (fra.isDetached()) {
				transaction.attach(fra);
			}
		}
		for (int i = 1; i <= 4; i++) {
			Fragment f = manager.findFragmentByTag("ss" + i);
			if (i == Byid) {
				continue;
			} else {
				if (f != null) {
					transaction.detach(f);
				}
			}
		}
		transaction.commitAllowingStateLoss();
		currType = Byid;
	}

	@Override
	public void onClick(View v) {
        resetImageView();
		switch (v.getId()) {
		case R.id.ShouYe:
            index.setImageResource(R.drawable.icon1);
			SuiPian(1);
			break;
		case R.id.FenLei:
            category.setImageResource(R.drawable.icon6);
			SuiPian(2);
			break;
		case R.id.GouWu:
            cart.setImageResource(R.drawable.icon7);
			SuiPian(3);
			break;
		case R.id.Wo:
            my.setImageResource(R.drawable.icon8);
			SuiPian(4);
			break;
		}
	}
    public void resetImageView(){
        index.setImageResource(R.drawable.icon5);
        category.setImageResource(R.drawable.icon2);
        cart.setImageResource(R.drawable.icon3);
        my.setImageResource(R.drawable.icon4);
    }



}
